# -*- coding: utf-8 -*-

import re

from django.shortcuts import render,redirect

from django.http import HttpResponseRedirect,HttpResponse,Http404

from app_rbac import models as rbacmd

from django.contrib.auth.decorators import login_required

from django.views.decorators.csrf import csrf_exempt

from django.contrib.auth import authenticate,login,logout

from django.contrib.auth.models import User

from app_rbac import models


from app_cmdb.models import HostInfo

from django.db.models import Sum, Count

import datetime



#权限控制装饰器
def Perms_required(func):
    def wrapper(request,*args,**kwargs):
        #会话权限列表
        perms_list = request.session['perms_list']

        #请求url处理
        req_url = request.path

        url_list = req_url.strip('#').split('/')

        cur_urls = []
        for i in url_list:
            if re.search('=',i):
                pass
            else:
                cur_urls.append(i)

        cur_url = "/".join(cur_urls)

        #判断访问url是否存在权限列表中
        if cur_url in perms_list:
            print cur_url
            return func(request, *args, **kwargs)
        else:
            return HttpResponse('权限不足')

    return wrapper





@login_required
def Index(request):

    #时间
    now = datetime.datetime.now()
    A = now.strftime('%A')
    Y = now.strftime('%Y')
    m = now.strftime('%m')
    d = now.strftime('%d')
    H_M = now.strftime('%H:%M')


    #用户数量
    user_count = User.objects.aggregate(Count('id'))
    user_num = user_count['id__count']

    #主机数量
    host_count = HostInfo.objects.aggregate(Count('id'))

    host_num = host_count['id__count']

    return render(request,"base.html",locals())



def Login(request):
    msg = 'login'
    if request.method == 'POST':
        login_username = request.POST.get('username')
        login_passwd = request.POST.get('passwd')

        user = authenticate(username=login_username, password=login_passwd)
        if user:
            login(request, user)
            request.session['username'] = login_username

            # 获取会话用户角色
            user_role = models.UserInfo.objects.get(user=user).role

            # 获取用户拥有的权限
            perms_list = []

            for perms in user_role.perms.all():

                perms_list.append(perms.perms_url)

            request.session['perms_list'] = perms_list



            menu_one = []
            menu_two = []

            for perms in user_role.perms.all():
                perms_title = perms.perms_title
                perms_type = perms.perms_type
                perms_url = perms.perms_url
                perms_num = perms.perms_num
                pmenu_id = perms.pmenu_id
                perms_icon = perms.perms_icon

                if perms_type == u'一级菜单':
                    menu_one.append({'perms_title': perms_title, 'perms_url': perms_url, 'perms_num': perms_num,'perms_icon':perms_icon})
                else:
                    menu_two.append({'perms_title': perms_title, 'perms_url': perms_url, 'pmenu_id': pmenu_id,
                                     'perms_num': perms_num})


            menu_all_list = []
            for i in menu_one:
                perms_num = i['perms_num']
                menu_list = []
                for j in menu_two:
                    pmenu_id = j['pmenu_id']
                    if pmenu_id == perms_num:
                        menu_list.append(j)

                i['menu_two'] = menu_list

                menu_all_list.append(i)

            request.session['menu_all_list'] = menu_all_list

            return redirect('/')

        else:
            msg = "用户名或密码不正确"
            return render(request, "login.html", locals())
    else:
        return render(request, "login.html", locals())



def Logout(request):
    logout(request)
    msg = 'login'
    request.session.delete("username")
    return render(request, "login.html", locals())





